package top.xunfong.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xunfong.auth.domain.LoginBody;
import top.xunfong.auth.service.AuthenticationService;
import top.xunfong.common.core.constant.SecurityConstants;
import top.xunfong.common.core.domain.R;
import top.xunfong.common.core.exception.ServiceException;
import top.xunfong.satoken.util.LoginHelper;
import top.xunfong.common.core.domain.model.LoginUserInfo;
import top.xunfong.system.model.RemoteSysUserService;

/**
 * @author: xunfong
 * @date: 2025/10/17 17:33
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Resource
    private RemoteSysUserService remoteSysUserService;

    @Override
    public String getVerificationCode(String phonenumber) {
        return null;
    }

    @Override
    public String login(LoginBody loginBody) {
        R<LoginUserInfo> login = remoteSysUserService.login(loginBody.getUsername(), SecurityConstants.INNER);
        LoginUserInfo userInfo = null;
        if (ObjectUtil.isNotNull(login) && ObjectUtil.isNotNull(login.getData())) {
            userInfo = login.getData();
            boolean checkpw = BCrypt.checkpw(loginBody.getPassword(), userInfo.getPassword());
            if (checkpw) {
                // 鉴权通过，返回token
                LoginHelper.login(userInfo);
                return StpUtil.getTokenValue();
            }

        }
        throw new ServiceException("用户名或密码错误");
    }
}
